<?php

/*
 * Copyright © 2010 - 2012 Modo Labs Inc. All rights reserved.
 *
 * The license gover    ning the contents of this file is located in the LICENSE
 * file located at the root directory of this distribution. If the LICENSE file
 * is missing, please contact sales@modolabs.com.
 *
 */

class FacebookDataRetriever extends URLDataRetriever
{
    protected $DEFAULT_PARSER_CLASS='JSONDataParser';
    protected $user;
    protected $clientId = '580461038637574';
    protected $clientSecret = 'b458a05eb3c4ce17e1c397c7d7f4509b';
    protected $accessToken;

    public function getUser($userID)
    {
        $this->setBaseURL(sprintf('https://graph.facebook.com/%s/', $userID));
        $this->setOption('action', 'user');
        return $this->getData();
    }
    
    public function getFriends($userID){
        $this->requiresAccessToken();
        //$json = json_decode(file_get_contents('https://graph.facebook.com/me/friends?access_token='.$this->accessToken), true);
        $this->setBaseURL(sprintf('https://graph.facebook.com/%s/friends?access_token=%s&fields=id', $userID, $this->accessToken));
        $this->setOption('action', 'friends');
        return $this->getData();
    }
    
    private function requiresAccessToken() {
    	if (!$this->accessToken) {
            $this->clearInternalCache();
            $this->setBaseURL('https://graph.facebook.com/oauth/access_token');
            $this->addParameter('client_id', $this->clientId);
            $this->addParameter('client_secret', $this->clientSecret);
            $this->addParameter('grant_type', 'client_credentials');
            $this->setOption('action', 'getAccessToken');
            $response = $this->getResponse();
    	    list($name, $token) = explode("=", $response->getResponse());
            if (!$token) {
                throw new KurogoDataException("Unable to retrieve facebook access token");
            }
            $this->accessToken = $token;
            $this->clearInternalCache();
    	}
    	return $this->accessToken;
    }          
}

